<template>
   <div id="search-history-page" class="search-history-box" @tap.stop>
    <mobileSearch ref="searchRef" :showCancle='true' :isSearch="true" @valChange="valChange" @handleSearch="handleSearch" @handleCancal="handleCancal"
      @handleFocus="closeSelectBox"></mobileSearch>
    <template v-if="(!searchItem.type && !searchItem.historyName) || !isKeyEnter">
      <div class="classify-item-title">
        <div class="title">{{$t('message.text.commonSearch')}}</div>
      </div>
      <div class="classify-search-items">
        <div v-for="(item,index) in quickList" :key="index" class="search-item search-item-hover" @click="quickGoSearch(item)">{{item.name}}</div>
      </div>
      <div class="classify-item-title">
        <div class="title">{{$t('message.text.historySearch')}}</div>
        <svg class="icon" aria-hidden="true" @click="delHistory()">
          <use xlink:href="#keowledge-mobile-qingchulishijilu"></use>
        </svg>
      </div>
      <div class="histroy-search-items">
        <div v-for="(item,index) in historyList" :key="index" class="search-item search-item-hover" @click="goSearch(item)">{{item.historyName}}</div>
      </div>
    </template>
    <template v-else>
      <div class="classify-item-title" @click="closeSelectBox()">
        <div class="title">{{$t('message.text.searchResult')}}</div>
      </div>
      <div class="classify-type-list">
        <div class="type-list-item" v-for="(itemL,indexL) in optionList" :key="indexL" @click="openOrClose(itemL)"
          :class="[currentOpenItem.type==itemL.type&&'type-list-item-active']">
          {{itemL.value?$t(findByvalue(itemL.Option,itemL.value)):$t(itemL.isNullLabel)}}
          <svg class="icon" aria-hidden="true">
            <use xlink:href="#keowledge-mobile-a-zu141"></use>
          </svg>
        </div>
      </div>
      <div class="search-content-list" style="height:calc(100vh - 10.3125rem)">
        <mobileScroll :ops="scrollOps" v-if="searchContentList!=0"
          :openPullDown="true" :openUpload="isLoadMore" 
          @refreshStart="handleRS" @loadMoreStart="handleLoadStart">
          <div class="list-item" v-for="(item,index) in searchContentList" :key="index" @click="toview(item)">
            <div class="list-item-icon">
              <svg class="icon" aria-hidden="true">
                <use v-bind:xlink:href="getIcon(item.type,item.nameSuffix)"></use>
              </svg>
            </div>
            <div class="list-item-content">
              <div class="item-file-name" v-html="`${item.name}`"></div>
              <div class="item-content" v-html="item.content"></div>
              <div class="item-infos">
                <div class="time-name">
                  <div class="time">
                    <svg class="icon" aria-hidden="true">
                      <use xlink:href="#keowledge-mobile-shijian"></use>
                    </svg> {{item.createTime}}
                  </div>
                  <div class="name">
                    <svg class="icon" aria-hidden="true">
                      <use xlink:href="#keowledge-mobile-chuangjianren"></use>
                    </svg> {{item.authorName}}</div>
                </div>
                <div class="knowledge-name">
                  <svg class="icon" aria-hidden="true">
                    <use xlink:href="#keowledge-mobile-wendang"></use>
                  </svg> {{item.knowledgeName}}
                </div>
              </div>
            </div>
          </div>
        </mobileScroll>
        <jvs-empty v-if="searchContentList.length==0" imgSrc="@/assets/images/common/searchEmpty.png" :text="$t('message.empty.nullSearch')"></jvs-empty>
        <div class="select-type-box" v-if="openSelect">
          <div class="select-type-mark" @click="closeSelectBox()"></div>
          <div class="select-type-content">
            <div v-for="(item,index) in currentOpenItem.Option" :key="index" class="select-type-item"
              :class="[currentOpenItem.value == item.value &&'select-type-item-active']" @click="optionClick(item)">
              <span>{{$t(item.label)}}</span>
              <img>
            </div>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  toRefs,
  watch ,
  onMounted,
  getCurrentInstance
} from 'vue' 
import type {ComponentInternalInstance} from 'vue'
const instance: any = getCurrentInstance() as ComponentInternalInstance;
const proxy: any = instance.proxy as any; // 访问 proxy 属性
import { useHookI18n } from '@/hooks/i18n'
const { locale,$t } = useHookI18n()
import mobileSearch from './mobileSearch.vue'
import mobileScroll from './mobileScroll.vue'
import { useList } from '@/config/config'
import indexDB from '@/utils/indexDB.js'
import { setSessionStore,getSessionStore,delSessionStore } from '@/utils/store'
import { findByvalue } from '@/utils/util'
import { documentSearch } from '@/api/common'
import { useRoute, useRouter } from "vue-router"
const router = useRouter();
const route = useRoute()
const emit = defineEmits([""])
const props = defineProps({

})

const quickList = ref(useList)
const historyList = ref([])
const searchVal = ref('')
const isKeyEnter = ref(false)
const searchItem = ref({
  type:'',
  historyName:''
})
const optionList = ref([
  {
    value:'',
    defaultVal:'',
    type:'type',
    visible:false,
    isNullLabel:'message.placeholder.documentType',
    Option:[{
      label:'message.typeMenu.allType',
      value:''
    },{
      label:'message.typeMenu.text',
      value:'document_html'
    },{
      label:'message.typeMenu.form',
      value:'document_xlsx'
    },{
      label:'message.typeMenu.mindMap',
      value:'document_map'
    },{
      label:'message.typeMenu.process',
      value:'document_flow'
    },{
      label:'message.typeMenu.word',
      value:'office_doc'
    },{
      label:'message.typeMenu.excel',
      value:'office_xlsx'
    },{
      label:'message.typeMenu.pdf',
      value:'office_pdf'
    },{
      label:'message.typeMenu.ppt',
      value:'office_ppt'
    }],
  },{
    value:'1',
    defaultVal:'1',
    visible:false,
    type:'searchContentType',
    Option:[{
      label:'message.typeMenu.fuzzySearch',
      value:"1"
    },{
      label:'message.typeMenu.accurateSearch',
      value:"2"
    }],
  },{
    value:'',
    defaultVal:'',
    shareRole:null,
    visible:false,
    type:'shareRole',
    isNullLabel:'message.placeholder.libraryLevel',
    Option:[{
      label:'message.typeMenu.allLeves',
      value:""
    },{
      label:'message.typeMenu.wholeNetwork',
      value:"all"
    },{
      label:'message.typeMenu.enterprise',
      value:"register"
    },{
      label:'message.typeMenu.private',
      value:"user"
    }]
  },{
    value:'',
    defaultVal:'',
    timeScope:null,
    visible:false,
    isNullLabel:'message.text.modifiTime',
    type:'timeScope',
    Option:[{
      label:'message.typeMenu.allTimes',
      value:""
    },{
      label:'message.typeMenu.lastDay1',
      value:"ONE_DAY"
    },{
      label:'message.typeMenu.lastDay7',
      value:"SEVEN_DAY"
    },{
      label:'message.typeMenu.lastDay30',
      value:"ONE_MONTH"
    }]
  }
])
const searchContentList = ref([])
const currentOpenItem = ref({})
const openSelect = ref(false)
const routerList =ref([])
const isMove = ref(false)
const isMoveTime = ref(null)
const searchPage = ref({
  current:1,
  total:0,
  size:20
})
const searchRef = ref()
const knowledgeDB = ref(null)
const scrollOps = ref({
  click:true,
  observeDOM: true,
  probeType: 3,
  pullDownRefresh: {
    threshold: parseFloat(document.documentElement.style.fontSize) * 6.25,
    stop:  parseFloat(document.documentElement.style.fontSize) * 6.25
  },
  pullUpLoad: {
    threshold: parseFloat(document.documentElement.style.fontSize) * 3.125,
    stop:  parseFloat(document.documentElement.style.fontSize) * 3.125
  }
})
const isLoadMore = ref(true)

onMounted(()=>{
  routerList.value = getSessionStore({name:'mobileRouterList'}) || []
  document.documentElement.style.fontSize = (document.documentElement.clientWidth/24.375).toFixed(2)+'px'
  searchItem.value = getSessionStore({name:'searchObj'}) || {type:'',historyName:''}
  if(searchItem.value.type || searchItem.value.historyName){
    isKeyEnter.value = true
    documentSearchHandle()
  }
  indexDB.openDB('knowledgeDB',1,knowledgeDB.value,{name:'historyList',key:'historyListKey'}, function(db) {
    knowledgeDB.value = db
    indexDB.readAll(db,"historyList").then(res=>{
      historyList.value = res.reverse()
    })
  });
})
function handleRS(done){
  searchPage.value = {
    current:1,
    total:0,
    size:20
  }
  documentSearchHandle(done,true)
}
function handleLoadStart(done){
  if(searchPage.value.current*searchPage.value.size<searchPage.value.total) {
    searchPage.value.current += 1
    documentSearchHandle(done)
  }else{
    done()
  }
}
function valChange(val){
  searchVal.value = val
  let isBack = true
  optionList.value.forEach((item)=>{
    if(item.value!=item.defaultVal){
      isBack = false
    }
  })
  if(!val && !searchItem.value.type && isBack){
    isKeyEnter.value = false
    clearSearch()
  }else if(isKeyEnter.value){
    searchPage.value = {
      current:1,
      total:0,
      size:20
    }
    searchContentList.value = []
    documentSearchHandle()
  }
}
function handleSearch(val){
  if(val){
    let isRe = true
    historyList.value.forEach(element => {
      if(element.historyName == val){
        isRe = false
      }
    });
    if(isRe){
      indexDB.addData(
        knowledgeDB.value,
        "historyList",
        {
          historyListKey:new Date().getTime(),
          historyName:val
        },
        function() {
          goSearch({
            historyName:val
          })
          indexDB.readAll( knowledgeDB.value,"historyList").then(res=>{
            historyList.value = res.reverse()
            goSearch({
              historyName:val,
            })
          })
        }
      );
    }else{
      goSearch({
        historyName:searchVal.value
      })
    }
    inputFoucs.value = false
  }
}
function documentSearchHandle (done,isClear = false) {
  let obj = {}
  optionList.value.forEach(item=>{
    obj[item.type] = item.value
  })
  documentSearch({
    keyword:searchVal.value,
    size:searchPage.value.size,
    current:searchPage.value.current,
    search:false,
    isNotNull:true,
    ...obj
  }).then(res => {
    if(res.data.code == 0) {
      let temp = res.data.data.records
      if(isClear){
        searchContentList.value = []
      }
      searchContentList.value.push(...temp)
      searchPage.value.total = res.data.data.total
      setScrollOps()
      if(done) {
        done()
        proxy.$mobileToast({
          text:isClear?$t('message.message.refreshSuccess'):$t('message.message.loadSuccess'),
          top:'7rem'
        })
      }
    }
  }).catch(e=>{
    if(done) done()
  })
}
function setScrollOps(){
  setScrollOps.value = searchPage.value.current*searchPage.value.size<searchPage.value.total
}
function goSearch(item){
  isKeyEnter.value = true
  searchVal.value = item.historyName
  searchItem.value = {
    type:item.value,
    historyName:item.historyName
  }
  setSessionStore({name:'searchObj',content:searchItem.value})
  searchRef.value.setSearchVal(searchItem.value.historyName || '')
  documentSearchHandle()
}
function quickGoSearch(item){
  optionList.value[0].value = item.value || ''
  goSearch(item)
}
function moveList(){
  isMove.value = true
}
function handleCancal(){
  delSessionStore({name:'searchObj'})
  if(!isKeyEnter.value && !searchVal.value){
    let path  = '/mobile/index'
    if(routerList.value.length!=0){
      path = routerList.value.pop()
      setSessionStore({name:'mobileRouterList',content:routerList.value})
    }
    router.push(path)
    return
  }
  if(isKeyEnter.value){
    isKeyEnter.value = false
  }
  if(searchVal.value){
    searchVal.value = ''
  }
  optionList.value.forEach(item=>{
    item.value = item.defaultVal
  })
  searchItem.value = {
    type:'',
    historyName:''
  }
  clearSearch()
  closeSelectBox()
}
function clearSearch(){
  searchPage.value = {
    current:1,
    total:0,
    size:20
  }
  searchContentList.value = []
}
function openOrClose(item){
  if(item.type==currentOpenItem.value.type){
    closeSelectBox()
  }else{
    openSelect.value = true
    currentOpenItem.value = item
  }
}
function optionClick(item){
  currentOpenItem.value.value = item.value
  documentSearchHandle()
  closeSelectBox()
}
function closeSelectBox(event){
  isMove.value = false
  openSelect.value = false
  currentOpenItem.value = {}
}
function delHistory(){
  proxy.$mobileConfirm({
    text:$t('message.confirm.clearHistory'),
    cancal(callBack){
      callBack && callBack()
    },
    submit(){
      indexDB.clearData(knowledgeDB.value,"historyList",function(){
        historyList.value = []
      })
    }
  });
}
function toview(item){
  let routerList = getSessionStore({name:'mobileRouterList'}) || []
  let currentPath = route.fullPath
  if(routerList.indexOf(currentPath)!=-1){
    routerList.splice(routerList.indexOf(currentPath),1)
  }
  routerList.push(currentPath)
  setSessionStore({name:'mobileRouterList',content:routerList})
  router.push({
    path:'/mobile/viewfile',
    query:{
      knId:item.knowledgeId,
      type:item.type,
      docId:item.docId || item.id,
      nameSuffix:item.nameSuffix||'',
      fileName:item.name||item.dcName
    }
  })
}
</script>
<style lang="scss" scoped>
.search-history-box{
  padding: 1rem 0px 0px;
  .classify-item-title{
    padding: 0px .9375rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 1.25rem;
    .title{
      @include SourceHanSansCN-Bold;
      font-size: 1rem;
      color: #363b4c;
    }
    .icon{
      width: 1rem;
      height: 1rem;
    }
  }
  .classify-search-items{
    padding: 0px .9375rem;
    display: grid;
    grid-template-columns: repeat(4,1fr);
    column-gap:.8125rem;
    .search-item{
      margin-top: .75rem;
      background: #F5F6F7;
      border-radius: .25rem;
      height: 2.25rem;
      display: flex;
      align-items: center;
      justify-content: center;
      color:#363B4C;
      @include SourceHanSansCN-Regular;
      font-size: .875rem;
    }
  }
  .histroy-search-items{
    display: flex;
    flex-wrap: wrap;
    padding: 0px .9375rem;
    column-gap:.8125rem;
    .search-item{
      padding:0px 1rem;
      margin-top: .75rem;
      background: #F5F6F7;
      border-radius: .25rem;
      height: 2.25rem;
      display: flex;
      align-items: center;
      justify-content: center;
      color:#363B4C;
      @include SourceHanSansCN-Regular;
      font-size: .875rem;
    }
  }
  .classify-type-list{
    // margin-left: .9375rem;
    margin-top: .75rem;
    display: flex;
    overflow-x: auto;
    &::-webkit-scrollbar{height:0px;}
    // column-gap: .75rem;
    .type-list-item{
      margin-left: .75rem;
      min-width: 6.125rem;
      height: 2.25rem;
      width: 6.125rem;
      border-radius: .25rem;
      background: #f2f7ff;
      font-size: .875rem;
      color: #6F7588;
      display: flex;
      align-items: center;
      justify-content: center;
      // padding: 0px .5rem;
      @include SourceHanSansCN-Regular;
      .icon{
        margin-left: .75rem;
        min-width: .875rem;
        width: .875rem;
        height: .875rem;
      }
    }
    .type-list-item-active{
      color: #1E6FFF;
    }
  }
  .search-content-list{
    margin-top: 1rem;
    position: relative;
    ::v-deep(.list-item){
      padding-left: 1rem;
      // width: calc(100% - 1.875rem);
      display: flex;
      .list-item-icon{
        width: 1.375rem;
        height: 1.375rem;
        .icon{
          width: 1.375rem;
          height: 1.375rem;
        }
      }
      .list-item-content{
        padding: 0px 0px 1rem;
        margin-left: 13px;
        padding-right: .9375rem;
        border-bottom: 1px solid #EEEFF0;
        width: 100%;
        .item-file-name{
          color: #363B4C;
          font-size: .9375rem;
          margin-bottom: .3125rem;
          @include SourceHanSansCN-Medium;
        }
        .item-content{
          color:#575E73;
          font-size: .75rem;
          @include SourceHanSansCN-Regular;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          line-clamp: 2;
          -webkit-box-orient: vertical;
          word-break: break-all;
          line-height: 1rem;
        }
        .item-infos{
          padding:.5625rem 0px 0px;
          display: flex;
          align-items: center;
          font-size: .6875rem;
          color: #6F7588;
          justify-content: space-between;
          @include SourceHanSansCN-Regular;
          .icon{
            width:  .75rem;
            height: .75rem;
            margin-right: .125rem;
          }
          .time-name{
            display: flex;
            align-items: center;
            .time{
              display: flex;
              align-items: center;
            }
            .name{
              display: flex;
              align-items: center;
              margin-left: 1.25rem;
              max-width: 7.5rem;
              text-overflow: ellipsis;
              white-space: nowrap;
              overflow: hidden;
            }
          }
          .knowledge-name{
            display: flex;
            align-items: center;
          }
        }
      }
    }
    .list-item+.list-item{
      margin-top: 1rem;
    }
    .select-type-box{
      position: absolute;
      top: 0px;
      height: 100%;
      width: 100%;
      .select-type-mark{
        background: rgba(54,59,76,0.5);
        position: absolute;
        top: 0px;
        height: 100%;
        width: 100%;
        z-index: 1;
      }
      .select-type-content{
        background-color: #fff;
        border-radius: 0 0 .75rem .75rem;
        position: absolute;
        top: 0px;
        width: 100%;
        z-index: 2;
        padding:0 .9375rem .5rem .9375rem;
        max-height: calc(100vh - 18.75rem);
        overflow: auto;
        .select-type-item{
          color: #363B4C;
          font-size: 1rem;
          @include SourceHanSansCN-Regular;
          padding: .3125rem .75rem;
          margin: .6875rem 0px;
          height: 2rem;
          border-radius: .25rem;
          display: flex;
          align-items: center;
        }
        .select-type-item-active{
          color: #1E6FFF;
          background-color: #e4edff;
        }

      }

    }
  }
}
</style>